package cn.edu.sjtu.se.dslab.component.aadl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Set;

import cn.edu.sjtu.se.dslab.pojo.CodeGenerator;
import cn.edu.sjtu.se.dslab.util.Const;
/**
 * aadl代码生成器
 * @author sunke
 *
 */
public class AADLGenerator extends CodeGenerator{

	private final static String ELEMENT_LIST = "elementList";
	
	private final static String Interface_TemplateFile = "aadl.vm";
	
	
	
	public AADLGenerator() {
		super();
	}
	
	public AADLGenerator(String templateFile) {
		super(templateFile);
	}

	public boolean generateAADLToFile(String xml,String targetFile)throws IOException{
		template = ve.getTemplate(Interface_TemplateFile);
		AADLParser parser = new AADLParser();
		Set<AADLElement> elementList = parser.parseAADL(xml);
		
		vc.put(ELEMENT_LIST, elementList);
		
		FileWriter fWriter = null;
		try {
			File writeFile = getFile(targetFile);
			fWriter = new FileWriter(writeFile);
			if (template != null) {
				template.merge(vc, fWriter);
			}		
		}finally {
			try {
				fWriter.flush();
				fWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
	
	public boolean generateAADL(String xml,String fileName) throws IOException{
		String aadlPath = Const.AADL_GENERATE_PATH+fileName;
		String aadlRealPath = Const.ABSOLUTE_GENERATE_PATH
				+ aadlPath;
		//File file = getFile(aadlRealPath);
		return generateAADLToFile(xml, aadlRealPath);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			AADLGenerator generator = new AADLGenerator();
			String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><content><node><id>a0a17978-2df4-43aa-9a8a-2730536c298a</id><type>thread</type><name>main</name><dbid></dbid><parentid></parentid><haschild>false</haschild><x>216</x><y>158</y><height>100</height><width>100</width><properties><property><name>Period</name><value>20 Ms</value></property><property><name>Dispatch_Protocol</name><value>Periodic</value></property><property><name>Compute_Execution_Time</name><value>5 Ms .. 10 Ms</value></property></properties></node></content>";
			
			generator.generateAADL(xml,"D:/test.aadl");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
}
